//Page Object
const app = getApp();
const config = require('../../../utils/config');
const request = require('../../../utils/request');

Page({
  data: {
    colorTheme: app.globalData.colorTheme,
    teamsList:[]
  },

  /**
   * 页面显示生命周期函数
   */
  onShow(){
    this.getTeamsList();
  },

  /**
   * 获取用户所属团队列表
   */
  getTeamsList(){
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'teams/listTeamsByUser';
    wx.showLoading({
      title: '加载ing',
    });
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          teamsList: res.data
        });
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 跳转到创建队伍界面
   */
  toCreateTeam(){
    wx.navigateTo({
      url: './create-team/create-team'
    });
  },

  /**
   * 跳转到团队展示页面
   */
  toTeamInfo(e){
    let team = this.data.teamsList[e.currentTarget.dataset.index];
    let url;
    if(team.role === "队长"){
      url = './manage-team-info/manage-team-info?teamId=' + team.id;
    }else{
      url = '../../team-show-info/team-show-info?teamId=' + team.id;
    }
    wx.navigateTo({
      url: url
    });
  },

  /**
   * 退出队伍
   */
  singOut(e){
    let that = this;
    let teamid = e.currentTarget.dataset.teamid;
    let params = {
      mode: 2,
      teamsId: teamid
    }
    console.log(params);
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'teams/leave';
    wx.showLoading({
      title: '正在退队...',
    });
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.getTeamsList();
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 2000
        });
      };
    }).catch(err => {
      app.failFun(err);
    }).finally(res => {
      app.completeFun(res);
    });
  },

  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
});